package com.qixia.upload.util;

import cn.hutool.core.codec.Base64;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.qixia.upload.common.JWTConstant;
import com.qixia.upload.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

import static com.qixia.upload.common.JWTConstant.EXPIRATION_TOKEN_TIME;
import static com.qixia.upload.common.JWTConstant.TOKEN;


@Slf4j
public class JwtUtil {

    /**
     * JWT认证加密私钥(Base64加密)
     */
    private static final String ENCRYPT_JWT_KEY = "YmFsYW5jZS10b2tlbi1rZXk=";
    //token有效时间两小时

    public static String sign(String userId, String account, String name, String phone, String userType, String source) {
        // 帐号加JWT私钥加密
        String secret = account + new String(Base64.decodeStr(ENCRYPT_JWT_KEY));
        // 此处过期时间是以毫秒为单位，所以乘以1000
        Date date = new Date(System.currentTimeMillis() + Long.parseLong(String.valueOf(EXPIRATION_TOKEN_TIME)) * 1000);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        // 附带account帐号信息 -- 附带账号类型
        return JWT.create()
                .withClaim("account", account)
                .withClaim("userId", userId)
                .withClaim("userName", name)
                .withClaim("phone", phone)
                .withClaim("userType", userType)
                .withClaim("source", source)
                .withExpiresAt(date)
                .sign(algorithm);
    }

    /**
     * 校验token是否正确
     *
     * @param token Token
     * @return boolean 是否正确
     */
    public static boolean verify(String token) {
        try {

            // 帐号加JWT私钥解密
            String secret = getClaim(token, JWTConstant.USER_ACCOUNT) + Base64ConvertUtil.decode(ENCRYPT_JWT_KEY);
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
            log.error("JWT Verify Fail,message={},token={}", e.getMessage(), token);
            return false;
        }
    }

    /**
     * 获得Token中的信息无需secret解密也能获得
     *
     * @param token
     * @param claim
     * @return java.lang.String
     */
    public static String getClaim(String token, String claim) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            // 只能输出String类型，如果是其他类型返回null
            return jwt.getClaim(claim).asString();
        } catch (JWTDecodeException e) {
            log.error("解密Token中的公共信息出现JWTDecodeException异常:" + e.getMessage());
            throw new CustomException("Token错误:" + e.getMessage());
        }
    }

    /**
     * 获得userId解密也能获得
     *
     * @return java.lang.String
     */
    public static String getUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, JWTConstant.USER_ID);
    }
    public static String getAccount(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, JWTConstant.USER_ACCOUNT);
    }
    public static String getOpenId(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, JWTConstant.USER_ACCOUNT);
    }
    public static String getUserName(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, JWTConstant.USER_NAME);
    }
    public static String getUserType(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, JWTConstant.USER_TYPE);
    }
    public static String getUserPhone(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, JWTConstant.PHONE);
    }
    public static String getSource(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, JWTConstant.PHONE);
    }
    public static String getTokenInfo(HttpServletRequest request, String key) {
        String token = request.getHeader("Authorization");
        if(StringUtils.hasLength(token) && token.contains("Bearer")){
            token = token.replace("Bearer ","");
        }
        if (token == null) {
            token = request.getParameter("token");
        }
        // 获取当前Token的帐号信息
        return getClaim(token, key);
    }
    public static String getToken(HttpServletRequest request) {
        String token = request.getHeader(TOKEN);
        if (token == null) {
            token = request.getParameter("token");
            if (!StringUtils.hasLength(token)) {
                throw new CustomException("未登录");
            }
        }
        token = token.replace("Bearer ", "");
        return token;
    }
}
